package com.enjoy.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by HP on 2019/7/2.
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket();

        serverSocket.bind(new InetSocketAddress(10001));

        System.out.println("Server is start");
        while (true){
            new Thread(new ServerTask(serverSocket.accept())).start();
        }
    }
    private static class ServerTask implements Runnable{
        private Socket socket=null;
        public  ServerTask(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run() {
            try {
                ObjectInputStream inputStream=new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream=new ObjectOutputStream(socket.getOutputStream());


                String userName=inputStream.readUTF();
                System.out.println("Accept client message:"+userName);

                outputStream.writeUTF("Hello,"+userName);
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
